package top.shaozuo.geektime.consistent;

import java.util.Collection;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 一致性hash算法
 * 
 * @author shaozuo
 *
 */
public class ConsistencyHashCluster extends AbstractCluster {

	private SortedMap<Integer, ServerNode> allNodes = new TreeMap<>();

	@Override
	public void addNode(ServerNode node) {
		allNodes.put(hash(node.getIp()), node);
	}

	@Override
	public void removeNode(ServerNode node) {
		allNodes.remove(hash(node.getIp()), node);
	}

	@Override
	public ServerNode getNodeBy(String key) {
		int hash = hash(key);
		SortedMap<Integer, ServerNode> subMap = allNodes.tailMap(hash);
		Integer firstKey;
		if (subMap.isEmpty()) {
			firstKey = allNodes.firstKey();
		} else {
			firstKey = subMap.firstKey();
		}
		return allNodes.get(firstKey);
	}

	@Override
	public Collection<ServerNode> nodes() {
		return allNodes.values();
	}
}